package org.light.generator;

import java.util.ArrayList;
import java.util.List;

import org.light.domain.Domain;
import org.light.utils.SqlReflector;
import org.light.utils.StringUtil;

public class MysqlDBDefinitionGenerator extends DBDefinitionGenerator{

	public String generateDBSql(boolean createDB,boolean commentOn,String exportStr) throws Exception{
		List<String> exports = new ArrayList<>();
		String [] exportArr = exportStr.split(",");
		for (String str :exportArr) {
			exports.add(str);
		}
		// set up the database;
		if (commentOn == false) {
			StringBuilder sb = new StringBuilder();
			if (createDB == true){
				sb.append("drop database if exists ").append(this.getDbName()).append(";\n");
				sb.append("create database ").append(this.getDbName()).append("/*!40100 COLLATE 'utf8_general_ci' */;\n");
				sb.append("use ").append(this.getDbName()).append(";\n\n");
			}
				
			for (int i=0; i < this.getDomains().size();i++){
				Domain domain = this.getDomains().get(i);
				if (StringUtil.isBlank(exportStr)||exports.contains(domain.getStandardName())) {
					if (!(domain instanceof org.light.domain.Enum)) {
						sb.append(SqlReflector.generateTableDefinition(domain)).append("\n");
					}
				}
			}
			return sb.toString();
		} else {
			StringBuilder sb = new StringBuilder();
			if (createDB == true){
				sb.append("drop database if exists ").append(this.getDbName()).append(";\n");
				sb.append("create database ").append(this.getDbName()).append("/*!40100 COLLATE 'utf8_general_ci' */;\n");
				sb.append("use ").append(this.getDbName()).append(";\n\n");
			}
				
			for (int i=0; i < this.getDomains().size();i++){
				Domain domain = this.getDomains().get(i);
				if (StringUtil.isBlank(exportStr)||exports.contains(domain.getStandardName())) {
					if (!(domain instanceof org.light.domain.Enum)) {
						sb.append(SqlReflector.generateTableDefinitionWithComment(domain)).append("\n");
					}
				}
			}
			return sb.toString();
		}
	}
	
	public String generateDBSql(boolean commentOn) throws Exception{
		return generateDBSql(false, commentOn,null);
	}

	@Override
	public String generateDropTableSqls(boolean createNew,String exportStr) throws Exception {
		List<String> exports = new ArrayList<>();
		String [] exportArr = exportStr.split(",");
		for (String str :exportArr) {
			exports.add(str);
		}
		
		StringBuilder sb = new StringBuilder();
		for (int i=0; i < this.getDomains().size();i++){
			Domain domain = this.getDomains().get(i);
			if (StringUtil.isBlank(exportStr)||exports.contains(domain.getStandardName())) {
				if (!(domain instanceof org.light.domain.Enum)) {
					sb.append(SqlReflector.generateMariaDBDropTableStatement(domain)).append("\n");
				}
			}
		}
		sb.append("\n");
		return sb.toString();
	}
	
}
